package com.yz.book.controller;


import com.yz.book.entity.User;
import com.yz.book.service.CartService;
import com.yz.book.service.UserService;
import com.yz.book.utils.CookieUtils;
import com.yz.book.utils.JSONUtils;
import com.yz.book.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Collection;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ste
 * @since 2023-02-04 03:37:36
 */
@Controller
@RequestMapping("/cart")
public class CartController {


    @Autowired
    UserService userService;

    @Autowired
    CartService cartService;

    private User getCurrentUser(HttpServletRequest request){
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String currentUserAccount = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        User currentUser = userService.getUserByUsername(currentUserAccount);

        return currentUser;
    }

    @RequestMapping("add")
    @ResponseBody
    public String add(Integer productId, HttpServletRequest request) {
        User currentUser = getCurrentUser(request);
        cartService.addCart(currentUser.getId(), productId);

        return "ok";
    }

    @RequestMapping("all")
    @ResponseBody
    public Collection<Object> all(HttpServletRequest request) {
        User currentUser = getCurrentUser(request);
        Collection<Object> allItem = cartService.getItemByUserId(currentUser.getId());
        return allItem;
    }

    @RequestMapping("updateItemNum")
    @ResponseBody
    public void updateItemNum(Integer productId, HttpServletRequest request,Integer buyCount){
        //buyCount 取值  -1 ,1 ,0 对应操作为  购买数量 -1,+1,删除

        User currentUser = getCurrentUser(request);

        cartService.updateItemNum(currentUser.getId(),productId,buyCount);

    }

    @RequestMapping("calTotalPrice")
    @ResponseBody
    public BigDecimal calTotalPrice(@RequestParam("productIds[]") Integer[] productIds, HttpServletRequest request){

        User currentUser = getCurrentUser(request);
        BigDecimal totalPrice = cartService.calTotalPrice(currentUser.getId(), productIds);

        return totalPrice;
    }

    @RequestMapping("toOrderPreview")
    public String toOrderPreview(Integer[] productIds, Model model){
        System.out.println(productIds);
        String productIdsJson = JSONUtils.createJson(productIds);
        System.out.println(productIdsJson);

        //给前端传json数据
        model.addAttribute("productIds",productIdsJson);

        return "orderPreview";
    }



}

